<template>
  <div class="container">
    <el-row class="actions-wrapper">
      <el-col class="left" :xs="10" :sm="12">
        <h2 v-if="mode=='work'" class="mode-text">作业模式</h2>
        <!-- <el-button size="mini" class="new hidden-xs-only" @click="goBack"><img src="../assets/返回.png" alt="返回">返回</el-button> -->
        <el-button
          :disabled="mode=='work'"
          size="mini" class="open" @click="toggleProject"><img src="../assets/项目.png" alt="项目"><span class="hidden-xs-only">项目</span></el-button>
        <el-button size="mini" class="save" @click="saveProject"><img src="../assets/保存.png" alt="保存"><span class="hidden-xs-only">保存</span></el-button>
        <el-select disabled size="medium" class="selector hidden-sm-and-down" v-model="curLanguage" @change="checkProject" placeholder="请选择编译语言">
          <el-option v-for="(item, index) in examples" :key="index" :value="index"></el-option>
        </el-select>
        <h4 class="project-name hidden-sm-and-down" @click="renameProjectDialogVisible = true">{{ (curProject ? curProject.project_name : '') + ' (项目名称)' }}</h4>
      </el-col>
      <el-col class="right" :xs="14" :sm="12">
        <el-button size="mini" class="run" @click="runProject"><img src="../assets/run.png" alt="运行"><span class="hidden-xs-only">Run</span></el-button>
        <!-- <el-button size="mini" class="stop"><img src="../assets/stop.png" alt="停止">stop</el-button> -->
        <el-button size="mini" class="send" @click="openSendProjectDialog"><img src="../assets/发送.png" alt="发送"><span class="hidden-xs-only">提交</span></el-button>
        <el-button @click="showSettings=true" size="mini"><img src="../assets/设置.png" alt="设置"><span class="hidden-xs-only">设置</span></el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col v-if="questionId && text" :md="6" class="hidden-md-and-down question">
        <h3>题目描述</h3>
        <p class="content">
          {{ text }}
        </p>
        <h3>参考答案</h3>
        <pre class="content">{{ answer }}</pre>
      </el-col>
      <el-col :sm="24" :md="questionId && text ? 18 : 24">
        <div class="code-header">
          <div class="code-file-list">
            <div @click="manageFile(item)" v-for="item in files" :key="item.project_detail_id" class="code-file-name" :class="{ 'active': item.project_detail_id == curFile.project_detail_id }">
              <span>{{ item.file_name }}</span>
              <i @click.stop="removeFile(item)">×</i>
            </div>
          </div>
          <img @click="hasProject" src="../assets/开始编码界面添加.png">
        </div>
        <div ref="codeArea" class="code-area"
         :style="{fontSize: editorStyle.fontSize + 'px', fontFamily: editorStyle.fontFamily}">
        </div>
        <div class="termial-area">
          <terminal ref="terminal"></terminal>
        </div>
      </el-col>
    </el-row>
    <div class="mask" v-show="manageMask" @click="manageFiles = !manageFiles"></div>
    <el-row class="mask-container" v-show="manageMask">
      <transition
        :name="manageFiles ? 'slide-left' : 'slide-left'"
        @before-enter="manageMask = true"
        @after-leave="manageMask = false">
        <el-col v-if="manageFiles" class="files" :sm="24" :xs="24">
          <el-menu>
            <el-menu-item index="1" @click="newProjectDialog">
              <span slot="title">新建项目</span>
            </el-menu-item>
            <el-submenu index="2">
              <span slot="title">我的项目</span>
              <el-menu-item  class="receive-project" v-for="(item, index) in projects[0].children" :key="'myproject-item'+index"  :index="'2-'+index">
                 <span  @click="openProject({myproject_id:item.myproject_id}, item.received)" class="item-span">{{item.label}}</span>
                  <span @click="removeProject({project_id:item.myproject_id}, index)" class="menu-receive">删除</span>
              </el-menu-item>
            </el-submenu>
            <el-submenu index="3">
              <el-badge :value="projects[1].children.length" slot="title"><span>待接收项目</span></el-badge>
              <el-menu-item  class="receive-project" v-for="(item, index) in projects[1].children" :key="'reproject-item'+index"  :index="'2-'+index" @click="openProject({myproject_id:item.myproject_id}, item.received)">
                <span class="item-span">{{item.label}}</span>
                <span @click="receiveProject({myproject_id:item.myproject_id})" class="menu-receive">接收</span>
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </el-col>
      </transition>
    </el-row>
    <el-dialog
      title="发送"
      :visible.sync="sendProjectDialogVisible"
      custom-class="coding-page-dialog"
      @open="getMyCourse"
      center
      class="dialog_res">
      <el-form label-width="80px">
        <el-form-item class="form-item" label="课程:">
          <el-select @change="getStudents" size="mini" :disabled="mode=='work'" v-model="course" placeholder="请选择课程" style="width: 100%">
              <el-option v-for="(item, index) in courses" :key="index" :value="item.id" :label="item.course_name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item" label="发送给:">
          <el-select size="mini" :disabled="mode=='work'" v-model="account" placeholder="请选择发送的人" style="width: 100%">
              <el-option v-if="userInfo && userInfo.role=='1'" value="-1" label="老师"></el-option>
              <el-option v-else value="-1" label="全班同学"></el-option>
              <el-option value="-2" label="课堂作业"></el-option>
              <el-option v-if="userInfo.id != item.account_id" v-for="(item, index) in students" :key="index" :value="item.account_id" :label="item.real_name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sendProjectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendProject">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="curLanguage?'新建一个' + curLanguage + '语言项目':'新建项目'"
      :visible.sync="newProjectDialogVisible"
      custom-class="coding-page-dialog"
      @close="closeNewProjectDlg"
      center
      class="dialog_res">
      <el-form label-width="80px">
        <el-form-item label="项目语言">
          <el-select size="medium" class="selector" v-model="curLanguage" placeholder="请选择编译语言">
            <el-option v-for="(item, index) in examples" :key="index" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input
            placeholder="请输入项目名称"
            v-model="newProjectName"
            clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="mode!='work'" @click="newProjectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newProject">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="项目重命名"
      :visible.sync="renameProjectDialogVisible"
      custom-class="coding-page-dialog"
      center
      class="dialog_res">
      <el-form label-width="80px">
        <el-form-item label="项目名称">
          <el-input
            placeholder="请输入项目名称"
            v-model="newProjectName"
            clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renameProjectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="renameProject">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="新建文件"
      :visible.sync="newFileDialogVisible"
      custom-class="coding-page-dialog"
      center
      class="dialog_res">
      <el-form label-width="80px">
        <el-form-item label="文件名称">
          <el-input
            placeholder="请输入文件名称"
            v-model="newFileName"
            clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="newFileDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newFile">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="文件重命名"
      :visible.sync="renameFileDialogVisible"
      custom-class="coding-page-dialog"
      center
      class="dialog_res">
      <el-form label-width="80px">
        <el-form-item label="文件名称">
          <el-input
            placeholder="请输入文件名称"
            v-model="newFileName"
            clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renameFileDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="renameFile">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
     title="运行"
     custom-class="dialog-run"
     :visible="false"
     @open="runProject"
     class="dialog_res">
    </el-dialog>
    <el-dialog
     title="设置"
     :visible.sync="showSettings"
     custom-class="coding-page-dialog"
     center
     class="dialog_res">
      <el-form label-width="80px">
        <el-form-item label="主题">
          <el-select class="selector" v-model="editorStyle.theme" placeholder="请选择">
            <el-option value="default"></el-option>
            <el-option value="colorforth"></el-option>
            <el-option value="seti"></el-option>
            <el-option value="twilight"></el-option>
         </el-select>
        </el-form-item>
        <el-form-item label="字体">
          <el-select class="selector" v-model="editorStyle.fontFamily" placeholder="请选择">
            <el-option value="Helvetica">Helvetica</el-option>
            <el-option value="Tahoma">Tahoma</el-option>
            <el-option value="Serif">Serif</el-option>
            <el-option value="微软雅黑">微软雅黑</el-option>
            <el-option value="Droid Sans">Droid Sans</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字体大小">
          <el-input-number v-model="editorStyle.fontSize" :step="2" label="描述文字"></el-input-number>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import { getUserInfo, logout, getMyCourse, getStudents, getProjects, newProject, saveProject, receiveProject, openProject, runProject, sendProject, manageFile, guestCreateProject, guestRunProject,deleteUserProject } from '@/utils/api'

import { isMobile, getCookie } from '@/utils/fetch'

import terminal from './Terminal.vue'
/* eslint-disable */
/* global CodeMirror, Terminal, io */
export default {
  name: 'index',
  data () {
    return {
      examples: {
        'C': '#include<stdio.h>\n\nint main(){\n\tprintf("hello world!");\n\treturn 0;\n}',
        'C++': '#include<iostream>\nusing namespace std;\n\nint main() {\n\tcout<<"hello world!"<<endl;\n\treturn 0;\n}',
        'Java': 'public class HelloWorld {\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println("Hello World");\n\t}\n}',
        'Fortran': 'write(*,*) "Hello World!"'
      },
      newProjectName: '',
      newFileName: '',
      manageMask: false,
      showMask: false,
      manageFiles: false,
      showFiles: false,
      showTerminal: false,
      showSettings: false,
      newProjectDialogVisible: false,
      renameProjectDialogVisible: false,
      newFileDialogVisible: false,
      renameFileDialogVisible: false,
      sendProjectDialogVisible: false,
      curLanguage: null,
      lastLanguage: null,
      editorStyle: {
        fontFamily: 'Helvetica',
        fontSize: 24,
        theme: 'default'
      },
      course: null,
      account: null,
      students: [],
      // 运行结果
      runResult: {},
      // 文件列表
      files: [],
      // 当前文件
      curFile: null,
      // 当前项目
      curProject: null,
      // 程序列表
      projects: [{
        label: '我的项目',
        stop: true,
        children: []
      },{
        label: '待接收的项目',
        stop: true,
        children: []
      }]
    }
  },
  props: {
    questionType: String,
    questionId: [String, Number],
    text: String,
    answer: String,
    projectId: [Number, String],
    courseId: [Number, String]
  },
  watch: {
    curLanguage (to, from) {
      this.lastLanguage = from
    },
    'editorStyle.fontSize' (to, from) {
      setTimeout(() => {
        this.codeMirror && this.codeMirror.refresh()
      }, 0)
    },
    'editorStyle.fontFamily' (to, from) {
      setTimeout(() => {
        this.codeMirror && this.codeMirror.refresh()
      }, 0)
    },
    'editorStyle.theme' (to, from) {
      let codeMirror = this.$refs['codeArea'].querySelector('.CodeMirror')
      let classes = codeMirror.getAttribute('class')
      let newClasses = classes.replace(/cm-s-\S+/, 'cm-s-' + to)
      codeMirror.setAttribute('class', newClasses)
    },
    courses (to) {
      if (this.mode === 'work' && this.courseId) {
        this.course = this.courses.find(course => course.id.toString() === this.courseId.toString()).id
        if (this.questionType && this.questionType.toString() === '1') {
          this.account = '-2'
        } else if (this.questionType && this.questionType.toString() === '0') {
          this.account = '-1'
        }
      }
    },
    curProject (to) {
      if (to) {
        this.codeMirror.setOption('readOnly', false)
      } else {
        this.codeMirror.setOption('readOnly', 'nocursor')
      }
    }
  },
  components: {
    terminal
  },
  computed: {
    userInfo () {
      return this.$store.state.userInfo
    },
    isLogin () {
      return this.userInfo ? 1 : 0
    },
    courses () {
      return this.$store.state.courses
    },
    mode () {
      return !this.questionId ? 'free' : 'work'
    },
    isMobile () {
      return isMobile()
    }
  },
  methods: {
    async logout () {
      let res = await logout()
      if (res.error === '10') {
        this.$notify({
          title: '退出成功',
          message: res.result,
          type: 'success',
          duration: 3000
        })
        this.$store.commit('logout')
        this.$router.push('/login')
      } else {
        this.$notify({
          title: '退出失败',
          message: res.result,
          type: 'error',
          duration: 3000
        })
      }
    },
    async openSendProjectDialog () {
      if (this.isLogin) {
        if (this.curProject) {
          this.sendProjectDialogVisible = true
        } else {
          this.$notify({
            title: '你还没有操作的项目可以发送',
            type: 'error',
            duration: 3000
          })
        }
      } else {
        this.$notify({
          title: '你还没登陆，还不能进行发送操作',
          type: 'error',
          duration: 3000
        })
      }
    },
    closeNewProjectDlg () {
      console.log(this.mode)
      if (this.mode === 'work' && !this.curProject) {
        this.$router.go(-1)
      }
    },
    async getMyCourse () {
      let res = await getMyCourse()
      if (res.error === '10') {
        this.$store.commit('setCourses', res.result)
      } else {
        this.$notify({
          title: '获取课程出错',
          message: res.result,
          type: 'error',
          duration: 3000
        })
      }
    },
    async getStudents (id) {
      let res = await getStudents({course_id: id, status: 1})
      if (res.error === '10') {
        this.students = res.result
      } else {
        this.$notify({
          title: '获取课程成员出错',
          message: res.result,
          type: 'error',
          duration: 3000
        })
      }
    },
    async sendProject () {
      if (!this.course) {
        this.$notify({
          title: '发送失败',
          message: '请选择发送的课程',
          type: 'error',
          duration: 3000
        })
      } else if (!this.account) {
        this.$notify({
          title: '发送失败',
          message: '请选择发送对象',
          type: 'error',
          duration: 3000
        })
      } else {
        let sendType = this.account === '-1' ? '0' : '1'
        if (this.account.toString() === '-2') {
          sendType = '2'
        }
        let res = await sendProject({
          course_id: this.course,
          send_type: sendType,
          target_account_id: +this.account <= 0 ? -1 : this.account,
          project_id: this.curProject.project_id
        })
        if (res.error === '10') {
          this.$notify({
            title: '发送成功',
            message: '项目发送成功',
            type: 'success',
            duration: 3000
          })
          this.sendProjectDialogVisible = false
        } else {
          this.$notify({
            title: '发送项目出错',
            message: res.result,
            type: 'error',
            duration: 3000
          })
        }
      }
    },
    async runProject () {
      if (this.isLogin) {
        if (this.curProject) {
          this.files.map((file) => { if (file.project_detail_id === this.curFile.project_detail_id) { file.code = this.codeMirror.getValue() } })
          let save = await saveProject({ myproject_id: this.curProject.project_id, account_id: this.userInfo.id, programming_language: this.curProject.programming_language, project_name: this.curProject.project_name, files: this.files })
          if (save.error === '10') {
            let res = await runProject({ project_id: this.curProject.project_id })
            if (res.error === '10') {
              this.runResult = res.result
              // this.showTerminal = true
              // this.openProject()
              this.$refs.terminal.openTerminal(this.runResult)
            } else {
              this.$notify({
                title: '代码运行失败',
                message: res.result,
                type: 'error',
                duration: 3000
              })
            }
          }
        } else {
          this.$notify({
            title: '你还没有进行运行的项目',
            type: 'error',
            duration: 3000
          })
        }
      } else {
        if (this.curProject) {
          let res = await guestRunProject({ project_name: this.curProject.project_name, programming_language: this.curProject.programming_language, files: [{project_detail_id: -1, file_name: this.curFile.file_name, code: this.codeMirror.getValue()}] })
          if (res.error === '10') {
            this.runResult = res.result
            // this.showTerminal = true
            this.$refs.terminal.openTerminal(this.runResult)
          } else {
            this.$notify({
              title: '代码运行失败',
              message: res.result,
              type: 'error',
              duration: 3000
            })
          }
        } else {
          this.$notify({
            title: '你还没有进行运行的项目',
            type: 'error',
            duration: 3000
          })
        }
      }
    },
    async getProjects () {
      let res = await getProjects()
      if (res.error === '10') {
        for (let key in res.result) {
          res.result[key].label = res.result[key].project_name
          if (res.result[key].received) {
            this.projects[0].children.push(res.result[key])
          } else {
            this.projects[1].children.push(res.result[key])
          }
          if (this.projectId && this.projectId.toString() !== '-1' && res.result[key].myproject_id === parseInt(this.projectId)) {
            this.openProject({ myproject_id: this.projectId }, true)
          }
        }
      } else {
        this.$notify({
          title: '读取项目信息失败',
          message: res.result,
          type: 'error',
          duration: 3000
        })
      }
    },
    async receiveProject (id) {
      let res = await receiveProject({ project_id: id })
      if (res.error === '10') {
        let result = {}
        this.projects[1].children.map((item, index) => {
          if (item.myproject_id === id) {
            result.index = index
            result.content = item
            item.received = true
          }
        })
        this.projects[1].children.splice(result.index, 1)
        this.projects[0].children.push(result.content)
      } else {
        if (res.result[0] === '项目名重复') {
          this.$notify({
            title: '项目接收失败,项目名重复,需要进行重命名才能接受',
            message: `原因: ${res.result}`,
            type: 'error',
            duration: 3000
          })
          this.renameProjectDialogVisible = true
        } else {
          this.$notify({
            title: '项目接收失败',
            message: `原因: ${res.result}`,
            type: 'error',
            duration: 3000
          })
        }
      }
    },
    async removeProject (params, index){
      let res = await deleteUserProject(params)
      if(res.error === '10'){
        this.projects[0].children.splice(index, 1)
      }
    },
    async openProject (item, isReceived) {
      console.log(item, isReceived)
      if (!item.stop) {
        if (!item.received && !isReceived) {
          await this.receiveProject(item.myproject_id)
        }
        await this.openProjectById(item.myproject_id)
      }
    },
    async openProjectById (projectId) {
      console.log('触发openProjectById')
      let res = await openProject({ project_id: projectId })
      if (res.error === '10') {
        this.curProject = res.result
        this.files = res.result.files
        this.curLanguage = res.result.programming_language
        this.curFile = res.result.files[0]
        this.codeMirror.setValue(this.curFile.code)
        this.manageFiles = false
      } else {
        this.$notify({
          title: '项目打开失败',
          message: `原因: ${res.result}`,
          type: 'error',
          duration: 3000
        })
      }
    },
    async newProject () {
      if (!this.newProjectName) {
        this.$notify({
          title: '项目名称不得为空',
          type: 'error',
          duration: 3000
        })
      } else {
        if (this.isLogin) {
          let res = await newProject({ programming_language: this.curLanguage, project_name: this.newProjectName, ti_id: this.questionId ? parseInt(this.questionId) : -1, type: this.questionType ? this.questionType : '2' })
          if (res.error === '10') {
            this.$notify({
              title: '新建成功',
              message: '项目创建成功',
              type: 'success',
              duration: 3000
            })
            // 清除之前的main文件
            this.files = [];
            if (this.projectId && this.projectId.toString() === '-1') {
              this.$router.push({ name: 'homework', params: { questionId: this.questionId, text: this.text, questionType: this.questionType, projectId: res.result.project_id } })
            }
            this.newProjectDialogVisible = false
            this.newProjectName = ''
            this.curProject = res.result
            this.curFile = { code: res.result.code, file_name: res.result.file_name, project_detail_id: res.result.project_detail_id }
            this.codeMirror.setValue(this.curFile.code)
            this.projects[0].children.push({ label: res.result.project_name, myproject_id: res.result.project_id, programming_language: res.result.programming_language, project_name: res.result.project_name, received: true })
            this.files.push(this.curFile)
          } else {
            this.$notify({
              title: '项目新建失败',
              message: `原因: ${res.result}`,
              type: 'error',
              duration: 3000
            })
          }
        } else {
          let res = await guestCreateProject({ project_name: this.newProjectName, programming_language: this.curLanguage })
          if (res.error === '10') {
            this.$notify({
              title: '新建成功',
              message: '项目创建成功',
              type: 'success',
              duration: 3000
            })
            // 清除之前的main文件
            this.files = [];
            this.newProjectDialogVisible = false
            this.newProjectName = ''
            this.curProject = res.result
            this.curFile = { code: res.result.code, file_name: res.result.file_name }
            this.codeMirror.setValue(this.curFile.code)
            this.files.push(this.curFile)
          } else {
            this.$notify({
              title: '项目新建失败',
              message: `原因: ${res.result}`,
              type: 'error',
              duration: 3000
            })
          }
        }
      }
    },
    async saveProject () {
      if (this.isLogin) {
        if (this.curProject) {
          this.files.map((file) => { if (file.project_detail_id === this.curFile.project_detail_id) { file.code = this.codeMirror.getValue() } })
          let res = await saveProject({ myproject_id: this.curProject.project_id, account_id: this.userInfo.id, programming_language: this.curProject.programming_language, project_name: this.curProject.project_name, files: this.files })
          if (res.error === '10') {
            this.$notify({
              title: '保存成功',
              message: '项目保存成功',
              type: 'success',
              duration: 3000
            })
            this.curProject.files = this.files
          } else {
            this.$notify({
              title: '项目保存失败',
              message: `原因: ${res.result}`,
              type: 'error',
              duration: 3000
            })
          }
        } else {
          this.$notify({
            title: '你还没有进行操作的项目可以保存',
            type: 'error',
            duration: 3000
          })
        }
      } else {
        this.$notify({
          title: '你还没登陆，还不能进行项目保存',
          type: 'error',
          duration: 3000
        })
      }
    },
    checkNewProject () {
      if (this.curLanguage) {
        this.newProjectDialogVisible = true
      } else {
        this.$notify({
          title: '请先选择要编辑的语言',
          type: 'error',
          duration: 3000
        })
      }
    },
    async renameProject () {
      if (this.isLogin) {
        if (!this.newProjectName) {
          this.$notify({
            title: '项目名称不得为空',
            type: 'error',
            duration: 3000
          })
        } else {
          let res = await saveProject({ myproject_id: this.curProject.project_id, account_id: this.userInfo.id, programming_language: this.curProject.programming_language, project_name: this.newProjectName, files: this.curProject.files })
          if (res.error === '10') {
            this.$notify({
              title: '重命名成功',
              message: '项目重命名成功',
              type: 'success',
              duration: 3000
            })
            this.renameProjectDialogVisible = false
            this.curProject.project_name = this.newProjectName
            this.projects[0].children.map((item) => {
              if (item.myproject_id === this.curProject.project_id) {
                item.label = item.project_name = this.newProjectName
              }
            })
            this.projects[1].children.map((item) => {
              if (item.myproject_id === this.curProject.project_id) {
                item.label = item.project_name = this.newProjectName
              }
            })
            this.newProjectName = ''
          } else {
            this.$notify({
              title: '项目重命名失败',
              message: `原因: ${res.result}`,
              type: 'error',
              duration: 3000
            })
          }
        }
      } else {
        this.$notify({
          title: '还没登陆不能对项目进行重命名',
          type: 'error',
          duration: 3000
        })
      }
    },
    checkProject () {
      if (!this.questionId) {
        if (this.curProject) {
          this.$confirm('你是想新建一个新的' + this.curLanguage + '语言的项目并保存当前项目吗？', '警告', {
            type: 'warning'
          }).then(() => {
            this.saveProject()
            this.newProjectDialogVisible = true
          }).catch(() => {
            this.curLanguage = this.lastLanguage
          })
        } else {
          if (this.curLanguage) {
            this.$confirm('你还没创建项目，是否创建一个' + this.curLanguage + '语言的项目?', '警告', {
              type: 'warning'
            }).then(() => {
              this.newProjectDialogVisible = true
            }).catch(() => {
              this.curLanguage = this.lastLanguage
            })
          }
        }
      }
    },
    async newFile () {
      if (!this.newFileName) {
        this.$notify({
          title: '文件名称不得为空',
          type: 'error',
          duration: 3000
        })
      } else {
        let res = await manageFile({ action_type: '1', project_id: this.curProject.project_id, project_detail_id: null, file_name: this.newFileName })
        if (res.error === '10') {
          this.$notify({
            title: '新建成功',
            message: '文件新建成功',
            type: 'success',
            duration: 3000
          })
          this.newFileDialogVisible = false
          this.curFile = { code: '', file_name: this.newFileName, project_detail_id: res.result.project_detail_id }
          this.files.push(this.curFile)
          this.codeMirror.setValue(this.curFile.code)
        } else {
          this.$notify({
            title: '文件新建失败',
            message: `原因: ${res.result}`,
            type: 'error',
            duration: 3000
          })
        }
      }
    },
    async manageFile (item) {
      if (this.curFile.project_detail_id === item.project_detail_id) {
        this.renameFileDialogVisible = true
      } else {
        this.files.map((file) => { if (file.project_detail_id === this.curFile.project_detail_id) { file.code = this.codeMirror.getValue() } })
        this.curFile = item
        this.codeMirror.setValue(this.curFile.code)
      }
    },
    async renameFile () {
      if (!this.newFileName) {
        this.$notify({
          title: '文件名称不得为空',
          type: 'error',
          duration: 3000
        })
      } else {
        this.curProject.files.map((file) => { if (file.project_detail_id === this.curFile.project_detail_id) { file.file_name = this.newFileName } })
        let res = await saveProject({ myproject_id: this.curProject.project_id, account_id: this.userInfo.id, programming_language: this.curProject.programming_language, project_name: this.curProject.project_name, files: this.curProject.files })
        if (res.error === '10') {
          this.$notify({
            title: '重命名成功',
            message: '文件重命名成功',
            type: 'success',
            duration: 3000
          })
          this.renameFileDialogVisible = false
          this.files.find((file) => { if (this.curFile.project_detail_id === file.project_detail_id) { file.file_name = this.newFileName } })
          this.newFileName = ''
        } else {
          this.$notify({
            title: '项目重命名失败',
            message: `原因: ${res.result}`,
            type: 'error',
            duration: 3000
          })
        }
      }
    },
    async removeFile (item) {
      if (this.isLogin) {
        let res = await this.$confirm('是否确定删除该文件！！！', '警告', {
          type: 'warning'
        })
        if (res === 'confirm') {
          let res = await manageFile({ action_type: '0', project_id: this.curProject.project_id, project_detail_id: item.project_detail_id, file_name: item.file_name })
          if (res.error === '10') {
            this.$notify({
              title: '删除成功',
              message: '成功删除文件',
              type: 'success',
              duration: 3000
            })
            let fileIndex = this.files.findIndex((file) => { return item.project_detail_id === file.project_detail_id })
            this.files.splice(fileIndex, 1)
            this.curFile = this.files[0]
            this.codeMirror.setValue(this.curFile.code)
          } else {
            this.$notify({
              title: '文件删除失败',
              message: `原因: ${res.result}`,
              type: 'error',
              duration: 3000
            })
          }
        }
      } else {
        this.$notify({
          title: '你还没登陆呢，不可以删除文件，如有需要请先建项目',
          type: 'error',
          duration: 3000
        })
      }
    },
    hasProject () {
      if (this.isLogin) {
        if (!this.curProject) {
          this.$notify({
            title: '请需要编辑的项目或者重新新建一个项目',
            type: 'error',
            duration: 3000
          })
        } else {
          this.newFileDialogVisible = true
        }
      } else {
        this.$notify({
          title: '你还没登陆呢，还不可以添加文件',
          type: 'error',
          duration: 3000
        })
      }
    },
    toggleFiles () {
      if (this.isLogin) {
        this.showFiles = !this.showFiles
      } else {
        this.$notify({
          title: '你还没登陆，还不能进行查询已有的项目',
          type: 'error',
          duration: 3000
        })
      }
    },
    toggleProject () {
      if (!this.questionId) {
        this.manageFiles = !this.manageFiles
      } else {
        this.$notify({
          title: '作业模式下不能再新建项目了',
          type: 'error',
          duration: 3000
        })
      }
    },
    async runCode () {
      // try {
      //   let res = await api.createTerminal()
      //   if (res.data.pid) {
      //     this.pid = res.data.pid
      //     this.showTerminal = true
      //   }
      // } catch (err) {
      //   console.error(err)
      // }
    },
    async goBack () {
      // 检查当前文件是否已经保存
      if (this.curCode.name.length <= 0) {
        try {
          var resultConfirm = await this.$confirm('当前文件尚未保存，是否保存？', {
            type: 'warning',
            cancelButtonText: '不保存'
          })
        } catch (err) {
          console.log(err)
        }
        if (resultConfirm === 'confirm') {
          let result = await this.saveFile()
          if (!result) {
            return
          }
        }
        this.codeMirror.setValue(this.examples[this.curLanguage])
        this.curCode.name = ''
      }
    },
    async saveFile () {
      if (this.curCode.name.length <= 0) {
        try {
          var resultFileName = await this.$prompt('请输入文件名', {
            customClass: 'savefile-msg'
          })
        } catch (err) { return }
        if (!resultFileName.value || resultFileName.value.length <= 0) {
          this.$message({
            message: '请输入文件名',
            type: 'warning'
          })
          return this.saveFile()
        }
        this.curCode.name = resultFileName.value
      }
      this.curCode.value = this.codeMirror.getValue()
      // try {
      //   let result = await api.saveFile(this.curLanguage, this.curCode.name, this.curCode.value)
      //   if (result.data.id) {
      //     this.$message({
      //       message: '保存成功',
      //       type: 'success'
      //     })
      //     return true
      //   } else {
      //     this.$message({
      //       message: '保存失败',
      //       type: 'error'
      //     })
      //     return false
      //   }
      // } catch (err) {
      //   if (err.message.indexOf('401') !== -1) {
      //     this.$message({
      //       message: '未登录，请登录',
      //       type: 'warning'
      //     })
      //     this.showLogin = true
      //     this.form.type = 'login'
      //   }
      // }
    },
    undo () {
      this.codeMirror.execCommand('undo') // 撤销上次更改
    },
    redo () {
      this.codeMirror.execCommand('redo') // 重做最后一次撤消的更改。
    },
    changeFontFamily (fontFamily) {
      this.editorStyle.fontFamily = fontFamily
    },
    changeFontSize (type) {
      if (type === 'mius') {
        this.editorStyle.fontSize -= 2
      } else {
        this.editorStyle.fontSize += 2
      }
    },
    newProjectDialog () {
      this.newProjectDialogVisible = true;
      this.manageMask = false;
    }
    // renderProjectTree (h, { node, data, store }) {
    //   return (<span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 15px;"><span><span>{node.label}</span></span>{ data.received === false ? <span><el-button style="font-size: 12px;" type="text" on-click={ () => this.receiveProject(data.myproject_id) }>接收</el-button></span> : ''}</span>)
    // }
  },
  async mounted () {
    this.editorStyle.fontSize = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ? 20 : 24
    if (this.isLogin) {
      this.getProjects()
      if (!this.courses.length) {
        this.getMyCourse()
      }
    } else {
      var cookie = getCookie('csrftoken')
      if(cookie){
        let res = await getUserInfo()
        if (res.error === '10') {
          this.getProjects()
          if (!this.courses.length) {
            this.getMyCourse()
          }
        } else {
          this.newProjectDialogVisible = true
        }
      }else{
        this.newProjectDialogVisible = true
      }
    }
    if (this.courseId && this.projectId && this.projectId.toString() === '-1') {
      this.newProjectDialogVisible = true
    }
    this.codeMirror = CodeMirror(document.querySelector('.code-area'), {
      lineNumbers: true,
      readOnly: this.projectId ? false : 'nocursor'
    })
    this.codeMirror.setSize('100%', '400px')
    if (this.projectId && this.projectId.toString() !== '-1') {
      this.openProjectById(this.projectId)
    }

    if (this.questionType && this.questionType.toString() === '1') {
      this.account = '-2'
    } else if (this.questionType && this.questionType.toString() === '0') {
      this.account = '-1'
    }

    console.log(this.$route)
    if(this.$route.params.projectId === -1){
      this.newProjectDialogVisible = true
    }else{
      this.openProjectById(this.$route.params.projectId)
    }
  }
}
</script>

<style lang="stylus">
.termial-area{
  padding: 0 5px;
  .el-collapse-item__header{
    font-size: 18px;
    padding-left: 20px; 
    padding-left: 20px; 
  }
  .el-collapse-item__content{
    padding-bottom: 0px;
  }
}
.slide-left-enter-active,
.slide-left-leave-active{
  transform translate(-400px, 0)
}
.container
  position relative
  .mode-text
    padding-right: 15px;
    color: #f00;
  .mask
    position absolute
    top 0
    left 0
    width 100%
    height 100%
    background rgba(0, 0, 0, 0.7)
    z-index 10
  .mask-container
      position absolute
      left 0
      top 0
      z-index 100
      height 100%
      width 60%
      max-width 400px;
    .item-span
      overflow hidden
      max-width 150px
      white-space: nowrap;
      text-overflow: ellipsis;
      @media screen and (max-width: 768px) {
        max-width: 100px
      }
    .blank
      height 100%
      div
        height 100%
    .files
      background #fff
      height 100%
      transition: 0.2s;
      max-height: 700px;
      overflow-y: auto;
      .tree
        margin-left 5%
        margin-top 10%

.actions-wrapper
  background #25a2cb
  height: 100%
  padding: 0 10px;
  .left{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 48px
  }
  .right
    display flex
    align-items center
    justify-content: flex-end;
    height: 48px
  .project-name
    color: #fff
    white-space nowrap
    padding 0 15px
    cursor pointer
    position relative
  .project-name:hover
    text-decoration underline
  .action-items
    height 100%
    display flex
    align-items center
    flex-wrap wrap
  .project, .save
    margin-right 15px
  .selector
    margin-left 15px
  button
    background #dafeff
    img
      width: 20px;
      height: 20px;
      margin-right: 6px;
      vertical-align middle
.question
  padding 15px
  border-right 2px solid #25a2cb
  min-height 500px
  .content
    margin-top 10px
    line-height 28px
    letter-spacing 1px
      white-space:pre-wrap
.code-area
  margin-left 10px
  font-size 1.3vmax
.code-header
  margin-left 10px
  font-size 0
  height 40px
  border-bottom 1px solid #999
  .code-file-list
    display inline-block
    height 38px
    line-height 38px
    font-size 1rem
    vertical-align top
    .code-file-name
      position relative
      display inline-block
      padding 0 20px 0 10px
      margin-top 2px
      margin-right 10px
      border-top 1px solid #999
      border-left 1px solid #999
      border-right 1px solid #999
      border-top-left-radius 5px
      border-top-right-radius 5px
      span
        display inline-block
        cursor pointer
      span:hover
        text-decoration underline
      i
        font-family "-apple-system","Helvetica Neue","Roboto","Segoe UI",sans-serif
        position absolute
        top 5px
        right 3px
        color #999
        display inline-block
        line-height 0
        cursor pointer
  img
    margin-top 10px
    margin-left 10px
    width 20px
    cursor pointer
.code-header .code-file-list .code-file-name.active
  background #999
  color #FFF
  i
    color #FFF
.CodeMirror
  height 600px !important
  font-family inherit
  @media screen and (max-width: 768px){
    height 400px !important
  }
.CodeMirror-gutter.CodeMirror-linenumbers
  width 3.9vmax!important
.CodeMirror-sizer
  margin-left 4.5vmax!important

.el-menu-item{
  color: #000;
}
.receive-project{
  color: #000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding 0 10px;
  .menu-receive{
    font-size: 12px;
    padding-right: 15px;
    color: #0195dd;
  }
}
.dialog_res > div{
  @media screen and (max-width: 768px) {
    width: 85%
  }
}
</style>
